<?php

namespace app\admin\controller\wechat;

use app\common\controller\Backend;

use phpQuery;

/**
 * 药品管理
 *
 * @icon fa fa-circle-o
 */
class Gather extends Backend
{

    public $wechatCats;
    protected $model = null;

    protected $relationSearch = true;
    protected $searchFields = 'id,title,author,';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wechat\Gather;
        $this->modelArticle = new \app\admin\model\wechat\Articles();
        $this->modelCats = new \app\admin\model\wechat\Cats();
        $this->wechatCats = collection($this->modelCats->select())->toArray();
    }

    public function index()
    {

        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where("cat_id =1 AND uid = " . $this->auth->id)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $cat_name = '';
                foreach ($this->wechatCats as $v2) {
                    if ($v['cat_id'] === $v2['id']) {
                        $cat_name = $v2['title'];
                    }
                }
                $list[$k]['cat_name'] = $cat_name;
            }

//            echo $this->model->getlastsql();
            $lists = $list->items();
            $total = $list->total();
            $result = array("total" => $total, "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add($ids = null)
    {

        if ($this->request->isAjax()) {

            $post = input("post.");
            $data = $post['row'];
            $this->getContent($data['url']);
//            $data['uid'] = $this->auth->id;
//            $this->model->insertGetId($data);
            $this->success('ok');
        }
        return $this->view->fetch();
    }

// http://www.guoman-admin.com/panel.php/wechat/gather/remoteAdd
    public function remoteAdd()
    {
//        $data = ['code':1];exit;
//        $data = "{
//        "content": "ai羽衣小天使上线",
//    "platform": "抖音",
//    "isRewrite": 0
//}";
//        exit;
        $dir = "F:/自媒体工具/wechatDownload2.4/下载/图Sir";
        $dir = "F:/公众号采集/微信公众号文章批量采集下载助手-V3版本源码-晴澜教育/壁纸Pro/html文件";
        $this->traverse($dir);
    }


    private function traverse($dir)
    {
        $files = scandir($dir);
        foreach ($files as $k => $file) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            $path = $dir . '/' . $file;
            $pathHas = $dir . '/has/';
            if (!is_dir($pathHas)) {
                mkdir($pathHas);
            }

            $pathNew = $pathHas . $file;
            if (is_dir($path)) {
//                traverse($path);
            } else {
//               echo "$k\n";
                if ($k >= 2) {
                    $this->getContent($path, $pathNew);
                }
            }
        }
    }

    private function getContent($path, $pathNew = '')
    {
        $html = file_get_contents(trim($path));


        require_once(APP_PATH . '/phpQuery/phpQuery.php');

        $doc = phpQuery::newDocumentHTML($html, 'utf-8');

        $data = [];

        //标题
        $data['title'] = trim($doc->find('h1#activity-name')->text());

        $gather_find = $this->model->where("title ='" . $data['title'] . "'")->find();

        // 查询是否重复
        if ($gather_find) {
            if ($pathNew) {
                rename($path, $pathNew);
            } else {
                $this->error('已存在');
            }

            return;
        }

        $imgsObject = $doc->find('.rich_pages');


        // 图片
        $source_imgs = array();
        foreach ($imgsObject as $node) {
            $src = $node->getAttribute("data-src");
            $imgInfo = getimagesize($src);
            $height = $imgInfo[1];
            if ($height > 200) {
                $source_imgs[] = $src;
            }
        }

        if ($source_imgs) {
            $data['imgs'] = implode(",", $source_imgs);
        }


        // 来源作者
        $data['author'] = trim($doc->find('#js_name')->text());

//        $data['addtime'] = date("Y-m-d H:i:s");

        // 来源地址
        $data['link'] = htmlspecialchars_decode($this->getSourceLink($doc));

        $data['uid'] = $this->auth->id;
//     $data['content'] = file_get_contents($data['link']);
        // 来源添加时间
//        $data['addtime'] = $this->getSourceAddtime(file_get_contents($data['link']));

        $data['addtime'] = $this->getSourceAddtime($html);

        $data['updatetime'] = date("Y-m-d H:i:s");

        if (!$pathNew) {
            $data['cat_id'] = 1;
        }

        $newId = $this->model->insertGetId($data);
        if ($newId && $pathNew) {
//            $path_has = 'has/'.$path;
//            echo $path;
//            echo "<hr>";
//            echo $pathNew;
            rename($path, $pathNew);
        }
        $this->success('ok');
    }

    private function getSourceLink($doc)
    {
        $text_link = trim($doc->find("meta[property='og:url']"));
        $pattern = '/content="(.+?)"/is';

        $source_link = "";
        if (preg_match($pattern, $text_link, $matches)) {
            $source_link = $matches[1];
        }
        return $source_link;
    }

    private function getSourceAddtime($html)
    {
        $pattern = '/var createTime = \'(.+?)\';/is';

        $result = date('Y-m-d H:i:s');
        if (preg_match($pattern, $html, $matches)) {
            $result = $matches[1];
        }
        return $result;
    }

    public function push($ids = null)
    {
        $ids = input('post.ids') ? input('post.ids') : $ids;
        // 是否已采集到aticles表
        $articleExist = $this->modelArticle->where("gather_id IN (" . $ids . ")")->select();
        if ($articleExist) {
            $articleArrayExist = collection($articleExist)->toArray();
            $strExist = '';
            foreach ($articleArrayExist as $v) {
                $strExist .= $v['gather_id'] . ",";
            }
            $this->error('已存在采集id：' . $strExist);
        }

        // 推送到aticles表
        $lists = collection($this->model->where("id IN (" . $ids . ")")->select())->toArray();
        $data['uid'] = $this->auth->id;
        $total = 0;
        foreach ($lists as $v) {
            $data['title'] = $v['title'];
            $data['imgs'] = $v['imgs'];
            $data['gather_id'] = $v['id'];
            $lastid = $this->modelArticle->insertGetId($data);
            if ($lastid) {
                $total++;
                $this->model->where("id = " . $v['id'])->update(array('article_id' => $lastid));
            }
        }
        $this->success('已采集数量：' . $total);
    }

// http://www.guoman-admin.com/panel.php/wechat/gather/updateGatherCatId
    public function updateGatherCatId()
    {
        $gathers = collection($this->model->where("cat_id is null or cat_id = 0")->select())->toArray();

        $cats = $this->wechatCats;

        foreach ($cats as $k => $v) {
            $cats[$k]['titles'] = explode(',', $v['titles']);
        }

        foreach ($gathers as $v) {
            $cat_id = $this->getCatIdByTitle($v['title'], $cats);
            $this->model->where("id =" . $v['id'])->update(array('cat_id' => $cat_id));
        }

//        print_r($cats);
        $this->success('采集成功');
    }

    public function getCatIdByTitle($title, $cats)
    {
        $cat_id = "-1";
        foreach ($cats as $v) {
            foreach ($v['titles'] as $v2) {
                if (strstr($title, $v2)) {
                    $cat_id = $v['id'];
                    break;
                }

            }

        }
        return $cat_id;
    }
    public function edit($ids = null)
    {

        if ($this->request->isAjax()) {
            $ids = $this->request->param('ids');
            $detail = $this->model->where("id =" . $ids)->find()->toArray();
            print_r($detail);

//            $this->model->where("id =" . $ids)->update($data);
//            $this->success('ok');
        }
        $row = $this->model->where("id =" . $ids)->find()->toArray();
        $imgs = explode(',',$row['imgs']);
//        print_r($row);
        $this->view->assign("row", $row);
        $this->view->assign("imgs", $imgs);
        return $this->view->fetch();
    }

}
